import React, { PureComponent, ReactDOM } from 'react';
import {
  ListView,
  WingBlank,
  Card,
  SwipeAction,
  Modal,
  NavBar,
  Icon,
} from 'antd-mobile';
import { connect } from '@@/plugin-dva/exports';
import { history } from 'umi';
import { Direction, Entity } from '@/services/searchParam';
import moment from 'moment';

// 展示数据组件
// @ts-ignore
@connect(({ global, central }) => ({ global, central }))
export default class List extends PureComponent {
  constructor(props: any) {
    super(props);
  }
  onEndReached = (event: any) => {
    // @ts-ignore
    let { page, totalPage } = this.props.central;
    // @ts-ignore
    if (event && page <= totalPage) {
      // @ts-ignore
      this.props.dispatch({
        type: 'central/getList',
        payload: {
          // @ts-ignore
          openId: localStorage.getItem('openId'),
          page: page,
        },
      });
    }
  };

  componentWillMount(): void {
    // @ts-ignore
    this.props.dispatch({
      type: 'central/resetSource',
    });
    // @ts-ignore
    this.props.dispatch({
      type: 'central/getList',
      payload: {
        // @ts-ignore
        openId: localStorage.getItem("openId"),
      },
    });
  }

  render():
    | React.ReactElement<any, string | React.JSXElementConstructor<any>>
    | string
    | number
    | {}
    | React.ReactNodeArray
    | React.ReactPortal
    | boolean
    | null
    | undefined {
    // @ts-ignore
    let { dataSource } = this.props.central;
    let index: number = dataSource.length - 1;
    // @ts-ignore
    const { startPoint, endPoint, start, end } = localStorage;
    const clock = require('../../../public/home/clock.png');
    const notice = require('../../../public/home/notice.png');
    const phone = require('../../../public/home/phone.png');

    const removePublish = (id: string) => {
      // @ts-ignore
      const { page } = this.props.central;
      Modal.alert('', '确定要删除吗？', [
        { text: '取消' },
        {
          text: '确定',
          onPress: () => {
            // @ts-ignore
            this.props.dispatch({
              type: 'central/removePublish',
              payload: {
                id: id,
              },
            });
          },
        },
      ]);
    };

    const showMore = () => {
      // @ts-ignore
      const { page, totalPage } = this.props.central;
      let showMore:string = '没有更多了';
      if (page < totalPage) {
        showMore = '加载中...'
      }
      return <div className={'show_more'}>{showMore}</div>;
    };

    const showRemark = (obj: any) => {
      let temp: string = '无';
      if (obj.remarks !== null && obj.remarks.length > 15) {
        temp = obj.remarks.substring(0, 15) + '...';
        return <div className={'remark'}>说明：{temp}</div>;
      } else {
        return <div className={'remark'}>说明：{obj.remarks}</div>;
      }
    };

    const showDate = (obj: any) => {
      const diffDays = moment(obj.departureTime).diff(
        moment(new Date()),
        'days',
      );
      if (diffDays === 1 || diffDays === 2) {
        return (
          <div style={{ fontSize: '1rem' }}>
            <img
              style={{ width: '1rem', height: '1rem' }}
              src={clock}
              alt={'时间'}
            />
            <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
            {moment(obj.departureTime).format('MM-DD')}
            {moment(obj.departureTime).diff(moment(new Date()), 'days') === 1
              ? '（明天）'
              : moment(obj.departureTime).diff(moment(new Date()), 'days') === 2
              ? '（后天）'
              : ''}
            <WingBlank style={{ display: 'inline-block' }} />
            {moment(obj.departureTime).format('HH:MM')}
            <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
            出发
          </div>
        );
      } else {
        return (
          <div className={'font-center'}>
            <img
              style={{ width: '1rem', height: '1rem' }}
              src={clock}
              alt={'时间'}
            />
            <span>
              <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
              {moment(obj.departureTime).format('YYYY-MM-DD HH:MM')}
              <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
              出发
            </span>
          </div>
        );
      }
    };

    const row = (rowData: any, sectionID: any, rowID: any): any => {
      if (index < 0) {
        index = dataSource.length - 1;
      }

      const obj = dataSource[index--];
      return (
        <SwipeAction
          style={{ backgroundColor: 'gray', margin: '3%' }}
          autoClose
          right={[
            {
              text: '取消',
              onPress: () => console.log('cancel'),
              style: { backgroundColor: '#ddd', color: 'white' },
            },
            {
              text: '删除',
              onPress: () => removePublish(obj.id),
              style: { backgroundColor: '#F4333C', color: 'white' },
            },
          ]}
        >
          <Card style={{ fontSize: '0.9rem' }}>
            <div
              key={rowID}
              style={{
                height: '100%',
                margin: '3%',
                overflowX: 'hidden',
                overflowY: 'hidden',
              }}
            >
              <div
                style={{
                  color: '#888',
                  borderBottom: '1px solid #F6F6F6',
                }}
              >
                <div>
                  <span style={{ color: 'orange' }}>从 </span>
                  <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
                  {obj.direction === Direction.STARTOEND ? start : end}
                  <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
                  <span>
                    {obj.direction === Direction.STARTOEND
                      ? obj.startRemarks
                      : obj.endRemarks}
                  </span>
                </div>
                <div>
                  <span style={{ color: 'orange' }}>到 </span>
                  <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
                  {obj.direction === Direction.STARTOEND ? end : start}
                  <WingBlank size={'sm'} style={{ display: 'inline-block' }} />
                  <span>
                    {obj.direction === Direction.STARTOEND
                      ? obj.endRemarks
                      : obj.startRemarks}
                  </span>
                </div>
              </div>
              <div style={{ display: '-webkit-box', padding: '5px 0' }}>
                <div style={{ width: '70%' }}>
                  {showDate(obj)}
                  <div style={{ marginTop: '8px' }}>
                    <img
                      style={{ width: '1rem', height: '1rem' }}
                      src={notice}
                      alt={'注意'}
                    />
                    <WingBlank
                      size={'sm'}
                      style={{ display: 'inline-block' }}
                    />
                    {obj.entity === Entity.CAR ? '车找人' : '人找车'} （
                    {obj.seatNumber}座）
                  </div>
                </div>
                <div
                  style={{ width: '30%', zIndex: 100 }}
                  onClick={() => {
                    alert(111);
                  }}
                >
                  <img
                    style={{
                      width: '30%',
                      height: '70%',
                      marginTop: '15%',
                      marginLeft: '37%',
                    }}
                    src={phone}
                    alt={'电话'}
                  />
                </div>
              </div>
              {showRemark(obj)}
            </div>
          </Card>
        </SwipeAction>
      );
    };

    const ds = new ListView.DataSource({
      rowHasChanged: (r1: any, r2: any) => r1 !== r2,
    });

    return (
      <div style={{ width: '100%', height: '100%' }}>
        <NavBar
          mode="dark"
          icon={<Icon type="left" />}
          onLeftClick={() => history.goBack()}
          rightContent={[<Icon key="1" type="ellipsis" />]}
        >
          我的发布
        </NavBar>
        <ListView
          dataSource={ds.cloneWithRows(dataSource)}
          renderRow={row}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={100}
        >
          {showMore()}
        </ListView>
      </div>
    );
  }
}
